package com.homegoods.orderinfodetail.ui.fragment;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.homegoods.orderinfodetail.OrderInfoApiUtils;
import com.homegoods.orderinfodetail.R;
import com.homegoods.orderinfodetail.adapter.GoodsParamAdapter;
import com.homegoods.orderinfodetail.model.GoodsDetailTypeBean;
import com.homegoods.orderinfodetail.model.OrderInfoDetailModel;
import com.homegoods.orderinfodetail.model.SKUValueModel;
import com.homegoods.orderinfodetail.model.SpeclistBean;
import com.homegoods.resource.dialog.BaseBottomSheetDialogFragment;
import com.homegoods.resource.widget.AddAndReduceWidget;
import com.kedll.library.util.MyUtils;
import com.kedll.library.util.StringUtil;
import com.kedll.library.widget.linearlistview.LinearListView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author QiQi
 * @ClassName: BaseChoiceDialog
 * @date 2018/9/22
 * @description
 */
abstract class BaseChoiceDialog extends BaseBottomSheetDialogFragment {
    /**
     * 展示的价格
     */
    private TextView mdetailsSelectPrice;
    /**
     * 活动价格
     */
    private TextView mtvActivityPrice;
    /**
     * 大洋
     */
    private TextView mtvDayang;
    /**
     * 库存
     */
    private TextView mdetailsResidueInfo;

    /**
     * 请选择
     */
    private TextView mdetailsSelectInfo;
    /**
     * 商品图片
     */
    private ImageView mdetailsSelectImage;

    private AddAndReduceWidget mCount;

    private List<SKUValueModel> multiSelectionList = new ArrayList<>();

    private GoodsParamAdapter adapter;

    private int iCount = 1;

    private String SelectTitle = "";
    private DismissCallBack callBack;
    private OrderInfoDetailModel mInfoModel;
    private List<OrderInfoDetailModel.CategoriesBean> detailTypeBeans;

//    private long marketprices;

    @Override
    protected void initView(View view) {
        mdetailsSelectPrice = findViewById(R.id.details_select_price);
        mtvActivityPrice = findViewById(R.id.tv_activity_price);
        mtvDayang = findViewById(R.id.tv_dayang);
        mdetailsResidueInfo = findViewById(R.id.details_residue_info);
        mdetailsSelectInfo = findViewById(R.id.details_select_info);
//        mdetailsSelectImage = findViewById(R.id.details_select_image);
        LinearListView mllList = findViewById(R.id.ll_list);

        adapter = new GoodsParamAdapter(getContext());
        mllList.setAdapter(adapter);

        adapter.setOnItemClickListener(BaseChoiceDialog.this::multiSelection);

        findViewById(R.id.details_close).setOnClickListener(v -> {
//            if (callBack == null) { //add if & else shibo.zheng
//                dismiss();
//            } else {
            callBack.getContent(mdetailsSelectInfo.getText().toString());
            this.dismiss();
//            }
        });
        findViewById(R.id.details_select_confirm).setOnClickListener(this::onAddToShoppingCart);

        mCount = findViewById(R.id.btn_count);

        mCount.initDefaultCount(iCount);

        mCount.setOnCallBack((v, count) -> {
            iCount = count;
//            setViewValue();
        });
    }

    @SuppressLint("CheckResult")
    @Override
    protected void loadData(Bundle arguments) {
        // 加载数据
        mInfoModel = (OrderInfoDetailModel) arguments.getSerializable("goods");
        detailTypeBeans = arguments.getParcelableArrayList("data");
        Log.d("zhengshibo", "loadData: minfoModel == " + mInfoModel.toString());
        Log.d("zhengshibo", "loadData: detailTypeBeans == " + JSON.toJSONString(detailTypeBeans));
        adapter.addAll(detailTypeBeans);
//        setViewValue();
    }

//    private void setViewValue() {
//        mtvActivityPrice.setText(String.format("￥%s", MyUtils.getActivityPrice(mInfoModel.getMinPrice(), mInfoModel.getPayCake()).multiply(new BigDecimal(iCount))));
//        mtvDayang.setText(String.format("%s积分", MyUtils.getActivityTegral(mInfoModel.getNowPrice(), mInfoModel.getPayCake()).multiply(new BigDecimal(iCount))));
//        mdetailsResidueInfo.setText(String.format("库存量%s件", mInfoModel.getSkuList().get(0).getStock()));    //modify shibo.zheng
//        mdetailsSelectPrice.setText(String.format("￥%s", mInfoModel.getMinPrice().multiply(new BigDecimal(iCount))));
//    }

    @Override
    public void dismiss() {
        super.dismiss();
        mInfoModel = null;
//        multiSelectionList = null;    //del shibo.zheng
        multiSelectionList.clear(); //add shibo.zheng
        detailTypeBeans = null;
    }

    private void multiSelection(SKUValueModel d, String titleName) {
        if (!this.multiSelectionList.contains(d)) {
            d.setSuperName(titleName);
            for (SKUValueModel bean : multiSelectionList) {
                if (titleName.equals(bean.getSuperName())) {
                    multiSelectionList.remove(bean);
                    break;
                }
            }
            this.multiSelectionList.add(d);
        } else {
            this.multiSelectionList.remove(d);
        }
        String selection = "";
        for (SKUValueModel bean : multiSelectionList) {
            if (TextUtils.isEmpty(selection)) {
                selection = bean.getName();
            } else {
                selection = selection + "," + bean.getName();
            }
        }
        mdetailsSelectInfo.setText(selection);

    }

    /**
     * 加入购物车
     *
     * @param view
     */
    void onAddToShoppingCart(View view) {
        //  调用添加购物车接口
        /**
         * {sid:'商品sid',serve:'上门服务',num:'商品数量',argument:'属性的名称',stadarry:[{title:'颜色',value:'黄色'}
         */
        String argument = "";
        for (SKUValueModel bean : multiSelectionList) {
            if (TextUtils.isEmpty(argument)) {
                argument = bean.getSuperName() + ":" + bean.getName();
            } else {
                argument = argument + "，" + bean.getSuperName() + ":" + bean.getName();
            }
//            marketprices += bean.getMarketprices();
        }
        /**
         *  * cmd=adit
         *      * AutoOD=1、0                              //自建订单
         *      * Money=34.88                              //金额
         *      * NCount=3                                 //数量
         *      * CmdtSid=15800327113                      //商品SID
         *      * SChoice=                                 //选参
         *      * AboutInf=0                               //说明
         */
        Map<String, Object> map = new HashMap<>();
        map.put("CmdtSid", mInfoModel.getId());
        map.put("NCount", iCount);
        map.put("SChoice", argument);
        map.put("AutoOD", "0");
        map.put("cmd", "adit");
//        map.put("Money", mInfoModel.getMinPrice().add(new BigDecimal(marketprices)));
        map.put("AboutInf", "服务");
        OrderInfoApiUtils.addCollectionShopCar(map, jsonObject -> {
            Toast toast = new Toast(view.getContext());
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.setView(LayoutInflater.from(view.getContext().getApplicationContext()).inflate(R.layout.info_suc_add_shop_car, null));
            toast.show();
            this.dismiss();
        }, throwable -> {
        });

    }


    public interface DismissCallBack {
        void getContent(String content);
    }

    public void setCallBack(DismissCallBack callBack) {
        this.callBack = callBack;
    }
}
